use serde::{Deserialize, Serialize};
use tauri::{State, Manager};
use std::collections::HashMap;
use std::sync::Mutex;

#[derive(Debug, Serialize, Deserialize)]
pub struct CreateTabRequest {
    pub url: String,
    pub account_id: Option<String>,
    pub platform: Option<String>,
    pub user_agent: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TabInfo {
    pub tab_id: String,
    pub url: String,
    pub title: String,
    pub account_id: Option<String>,
    pub platform: Option<String>,
    pub webview_id: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CookieData {
    pub name: String,
    pub value: String,
    pub domain: String,
    pub path: String,
    pub expires: Option<i64>,
    pub http_only: bool,
    pub secure: bool,
}

#[derive(Debug, Default)]
pub struct TabManager {
    tabs: Mutex<HashMap<String, TabInfo>>,
}

#[tauri::command]
pub async fn create_tab(
    request: CreateTabRequest,
    state: State<'_, TabManager>,
    app_handle: tauri::AppHandle,
) -> Result<TabInfo, String> {
    let tab_id = uuid::Uuid::new_v4().to_string();
    let webview_id = format!("webview_{}", tab_id);
    
    // 为每个标签页创建独立的数据目录
    let data_dir = app_handle
        .path()
        .app_data_dir()
        .unwrap()
        .join("sessions")
        .join(&tab_id);
    
    std::fs::create_dir_all(&data_dir).map_err(|e| format!("Failed to create data directory: {}", e))?;
    
    // 获取自定义User-Agent
    let user_agent = request.user_agent.unwrap_or_else(|| {
        get_platform_user_agent(request.platform.as_deref().unwrap_or("default"))
    });
    
    // 创建WebView（在Tauri 2.0中，我们需要使用WebviewWindow）
    // 注意：这里简化了实现，实际需要根据Tauri 2.0 API调整
    
    let tab_info = TabInfo {
        tab_id: tab_id.clone(),
        url: request.url,
        title: "新建标签页".to_string(),
        account_id: request.account_id,
        platform: request.platform,
        webview_id,
    };
    
    // 存储标签页信息
    state.tabs.lock().unwrap().insert(tab_id.clone(), tab_info.clone());
    
    Ok(tab_info)
}

#[tauri::command]
pub async fn close_tab(
    tab_id: String,
    state: State<'_, TabManager>,
    app_handle: tauri::AppHandle,
) -> Result<(), String> {
    let mut tabs = state.tabs.lock().unwrap();
    
    if let Some(tab_info) = tabs.remove(&tab_id) {
        // 清理数据目录
        let data_dir = app_handle
            .path()
            .app_data_dir()
            .unwrap()
            .join("sessions")
            .join(&tab_id);
            
        if data_dir.exists() {
            std::fs::remove_dir_all(&data_dir).map_err(|e| format!("Failed to clean data directory: {}", e))?;
        }
        
        // 这里应该关闭对应的WebView
        // 在Tauri 2.0中需要调用相应的API
        
        Ok(())
    } else {
        Err("Tab not found".to_string())
    }
}

#[tauri::command]
pub async fn navigate_tab(
    tab_id: String,
    url: String,
    state: State<'_, TabManager>,
) -> Result<(), String> {
    let mut tabs = state.tabs.lock().unwrap();
    
    if let Some(tab_info) = tabs.get_mut(&tab_id) {
        tab_info.url = url.clone();
        
        // 这里应该调用WebView的导航API
        // 在Tauri 2.0中需要相应的实现
        
        Ok(())
    } else {
        Err("Tab not found".to_string())
    }
}

#[tauri::command]
pub async fn get_tab_info(
    tab_id: String,
    state: State<'_, TabManager>,
) -> Result<Option<TabInfo>, String> {
    let tabs = state.tabs.lock().unwrap();
    Ok(tabs.get(&tab_id).cloned())
}

#[tauri::command]
pub async fn export_cookies(
    _tab_id: String,
    state: State<'_, TabManager>,
) -> Result<Vec<CookieData>, String> {
    // 这里应该从WebView的Cookie存储中获取Cookie
    // 由于Tauri 2.0的Cookie API限制，这里返回模拟数据
    
    let _tabs = state.tabs.lock().unwrap();
    
    // 模拟返回一些Cookie数据
    let cookies = vec![
        CookieData {
            name: "sessionid".to_string(),
            value: "mock_session_value".to_string(),
            domain: ".douyin.com".to_string(),
            path: "/".to_string(),
            expires: Some(chrono::Utc::now().timestamp() + 3600),
            http_only: true,
            secure: true,
        },
        CookieData {
            name: "user_token".to_string(),
            value: "mock_user_token".to_string(),
            domain: ".douyin.com".to_string(),
            path: "/".to_string(),
            expires: Some(chrono::Utc::now().timestamp() + 86400),
            http_only: false,
            secure: true,
        },
    ];
    
    Ok(cookies)
}

#[tauri::command]
pub async fn import_cookies(
    tab_id: String,
    cookies: Vec<CookieData>,
    state: State<'_, TabManager>,
) -> Result<(), String> {
    // 这里应该将Cookie导入到WebView的Cookie存储中
    // 由于Tauri 2.0的Cookie API限制，这里只是模拟实现
    
    let _tabs = state.tabs.lock().unwrap();
    
    println!("Importing {} cookies for tab {}", cookies.len(), tab_id);
    
    // 在实际实现中，这里应该调用Tauri的Cookie设置API
    
    Ok(())
}

#[tauri::command]
pub async fn clear_cookies(
    tab_id: String,
    state: State<'_, TabManager>,
) -> Result<(), String> {
    // 清理特定标签页的Cookie
    
    let _tabs = state.tabs.lock().unwrap();
    
    println!("Clearing cookies for tab {}", tab_id);
    
    // 在实际实现中，这里应该调用Tauri的Cookie清理API
    
    Ok(())
}

fn get_platform_user_agent(platform: &str) -> String {
    match platform {
        "抖音" => "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15".to_string(),
        "快手" => "Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36".to_string(),
        "小红书" => "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15".to_string(),
        "微博" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36".to_string(),
        "B站" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36".to_string(),
        _ => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36".to_string(),
    }
}